import React, { useState, useEffect } from 'react';
import { Modal, Input, message } from 'antd';
import RunAtTimePicker from '@components/run-at-time-picker';
import { addWeb } from '@api/task';
import { NAME_RE } from '@util/constants';
import PropTypes from 'prop-types';
import moment from 'moment';
import _ from 'lodash';
import './index.less';

const WebFingerModal = props => {
  const {
    selectedIps = [],
    selectedUrls = [],
    selectedSiteIds = [],
    visible = false,
    onClose
  } = props;
  const { TextArea } = Input;

  const [taskName, setTaskName] = useState('');
  // const [urgent, setUrgent] = useState(false);
  const [runAt, setRunAt] = useState({ isRunAt: false, time: moment().format('YYYY-MM-DD HH:mm') });
  const [taskNameError, setTaskNameError] = useState('');
  const [confirmLoading, setconfirmLoading] = useState(false);

  useEffect(() => {
    setTaskName('');
    setTaskNameError('');
    setRunAt({ isRunAt: false, time: moment().format('YYYY-MM-DD HH:mm') });
  }, [visible]);

  const targetEmpty = _.isEmpty(selectedIps) && _.isEmpty(selectedUrls);
  const targets = targetEmpty ? '全部目标' : selectedIps.concat(selectedUrls).join('\n');

  const onTaskNameChange = e => {
    const taskName = e.target.value;

    setTaskName(taskName);
    setTaskNameError('');

    if (!taskName) {
      setTaskNameError('任务名不能为空');
      return;
    }
    if (taskName.length > 32) {
      setTaskNameError('您输入的内容超过32个字符限制');
      return;
    }
    if (!NAME_RE.test(taskName)) {
      setTaskNameError('您输入的格式有误，仅支持中文、英文、数字、特殊字符 - 、— \\ _ / ：~');
      return;
    }
  };
  // const onUrgentChange = e => {
  //   setUrgent(e.target.checked);
  // };

  const onOk = () => {
    let scope = 'individual';
    if (!selectedSiteIds.length) {
      scope = 'all';
    }
    if (!taskName) {
      setTaskNameError('任务名不能为空');
      return;
    }
    if (taskNameError) {
      return;
    }
    const nowTime = moment();
    const { isRunAt, time } = runAt;
    if ((isRunAt && nowTime > moment(time)) || time === 'Invalid date') {
      return message.warning('您指定的时间有误，请重新选择');
    }
    /* eslint-disable  camelcase */
    const body = {
      scope,
      name: taskName.replace(/\s/g, ''),
      ips: selectedIps,
      site_ids: selectedSiteIds,
      // urgent,
      runAt
    };
    /* eslint-enable */
    setconfirmLoading(true);
    addWeb(body)
      .then(() => {
        message.success('下发任务成功');
        onClose();
      })
      .catch(({ type, message: messageString }) => {
        if (type === 'parsed') {
          message.error(messageString);
        } else {
          message.error('下发任务失败');
        }
      })
      .finally(() => {
        setconfirmLoading(false);
      });
  };

  const onRunAtChange = runAt => {
    setRunAt(runAt);
  };

  return (
    <Modal
      maskClosable={false}
      className="webfinger-modal"
      title="Web指纹探测"
      visible={visible}
      onOk={onOk}
      onCancel={onClose}
      confirmLoading={confirmLoading}
      destroyOnClose
    >
      <div className="wf-content">
        <div className="wf-content-ips">
          <span>探测目标</span>
          <div>
            <TextArea value={targets} autoSize={{ minRows: 4, maxRows: 8 }} disabled />
          </div>
        </div>
        <div className="wf-content-run-at">
          <RunAtTimePicker onChange={onRunAtChange} />
        </div>
        {/* <div className="wf-content-urgent">
          <Checkbox onChange={onUrgentChange} style={{ marginBottom: 16 }}>
            加急任务（优先执行，但不影响其它正在执行中的任务）
          </Checkbox>
        </div> */}
        <div className="wf-content-taskname">
          <span>任务名称</span>
          <Input
            value={taskName}
            onChange={onTaskNameChange}
            placeholder="请输入中文、英文、特殊字符或数字，不超过32个字符"
          />
          {taskNameError && <p className="validate-error">{taskNameError}</p>}
        </div>
      </div>
    </Modal>
  );
};

WebFingerModal.propTypes = {
  selectedIps: PropTypes.array,
  selectedUrls: PropTypes.array,
  selectedSiteIds: PropTypes.array,
  visible: PropTypes.bool,
  onClose: PropTypes.func
};

export default WebFingerModal;
